<template>
  <div class="category-analysis">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>分类数据统计</h1>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 分类筛选 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="分类选择">
              <el-select v-model="filterForm.category" placeholder="选择分类" clearable>
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyFilter">应用筛选</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 统计图表 -->
        <el-row :gutter="20" class="charts-section">
          <el-col :span="24">
            <el-card>
              <template #header>
                <span>三级分类商品数量分布 (Top 20)</span>
              </template>
              <div class="chart-container">
                <v-chart :option="categoryCountOption" style="height: 500px;" />
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="charts-section">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>三级分类平均价格对比 (Top 10)</span>
              </template>
              <div class="chart-container">
                <v-chart :option="categoryPriceOption" style="height: 400px;" />
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>三级分类价格区间分布</span>
              </template>
              <div class="chart-container">
                <v-chart :option="categoryPriceRangeOption" style="height: 400px;" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分类详细数据 -->
        <el-card class="detail-card">
          <template #header>
            <span>分类详细统计</span>
          </template>
          <el-table :data="categoryDetails" style="width: 100%">
            <el-table-column prop="category" label="分类名称" />
            <el-table-column prop="productCount" label="商品数量" />
            <el-table-column prop="avgPrice" label="平均价格">
              <template #default="scope">
                ¥{{ scope.row.avgPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="minPrice" label="最低价格">
              <template #default="scope">
                ¥{{ scope.row.minPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="maxPrice" label="最高价格">
              <template #default="scope">
                ¥{{ scope.row.maxPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="commentCount" label="评论总数" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="viewCategoryDetail(scope.row.category)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 分类详情对话框 -->
        <el-dialog
          v-model="detailDialogVisible"
          title="分类详情"
          width="80%"
        >
          <div v-if="selectedCategoryDetail">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="分类名称">
                {{ selectedCategoryDetail.category }}
              </el-descriptions-item>
              <el-descriptions-item label="商品总数">
                {{ selectedCategoryDetail.productCount }}
              </el-descriptions-item>
              <el-descriptions-item label="平均价格">
                ¥{{ selectedCategoryDetail.avgPrice }}
              </el-descriptions-item>
            </el-descriptions>
            
            <el-table :data="selectedCategoryDetail.products" style="margin-top: 20px;">
              <el-table-column prop="title" label="商品名称" />
              <el-table-column prop="price" label="价格">
                <template #default="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="author" label="作者" />
              <el-table-column prop="publisher" label="出版社" />
              <el-table-column prop="commentCount" label="评论数" />
            </el-table>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'

use([CanvasRenderer, BarChart, PieChart, GridComponent, TooltipComponent, LegendComponent])

export default {
  name: 'CategoryAnalysis',
  components: {
    VChart
  },
  setup() {
    const filterForm = ref({
      category: ''
    })

    const categories = ref([])
    const categoryDetails = ref([])
    const detailDialogVisible = ref(false)
    const selectedCategoryDetail = ref(null)

    const categoryCountOption = ref({
      title: {
        text: '分类商品数量分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '商品数量',
          type: 'bar',
          data: []
        }
      ]
    })

    const categoryPriceOption = ref({
      title: {
        text: '三级分类平均价格对比 (Top 10)',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '价格 (元)'
      },
      series: [
        {
          name: '平均价格',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    })

    const categoryPriceRangeOption = ref({
      title: {
        text: '三级分类价格区间分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '价格区间',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 0, name: '0-50元' },
            { value: 0, name: '50-100元' },
            { value: 0, name: '100-200元' },
            { value: 0, name: '200元以上' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })

    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category/list')
        categories.value = response.data
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    }

    const fetchCategoryAnalysis = async () => {
      try {
        const response = await axios.get('/api/category/analysis', {
          params: filterForm.value
        })
        categoryDetails.value = response.data.details
        
        // 更新图表数据
        categoryCountOption.value.xAxis.data = response.data.chartData.categories
        categoryCountOption.value.series[0].data = response.data.chartData.counts
        
        // 只显示前10个分类的价格对比
        const top10Categories = response.data.chartData.categories.slice(0, 10)
        const top10Prices = response.data.chartData.prices.slice(0, 10)
        categoryPriceOption.value.xAxis.data = top10Categories
        categoryPriceOption.value.series[0].data = top10Prices
        
        // 计算价格区间分布
        calculatePriceRangeDistribution(response.data.details)
      } catch (error) {
        console.error('获取分类分析数据失败:', error)
      }
    }

    const calculatePriceRangeDistribution = (details) => {
      const priceRanges = {
        '0-50元': 0,
        '50-100元': 0,
        '100-200元': 0,
        '200元以上': 0
      }
      
      details.forEach(item => {
        const avgPrice = item.avgPrice
        if (avgPrice < 50) {
          priceRanges['0-50元']++
        } else if (avgPrice < 100) {
          priceRanges['50-100元']++
        } else if (avgPrice < 200) {
          priceRanges['100-200元']++
        } else {
          priceRanges['200元以上']++
        }
      })
      
      categoryPriceRangeOption.value.series[0].data = Object.entries(priceRanges).map(([name, value]) => ({
        name,
        value
      }))
    }

    const refreshData = () => {
      fetchCategories()
      fetchCategoryAnalysis()
    }

    const applyFilter = () => {
      fetchCategoryAnalysis()
    }

    const resetFilter = () => {
      filterForm.value.category = ''
      fetchCategoryAnalysis()
    }

    const viewCategoryDetail = async (category) => {
      try {
        const response = await axios.get(`/api/category/detail/${category}`)
        selectedCategoryDetail.value = response.data
        detailDialogVisible.value = true
      } catch (error) {
        console.error('获取分类详情失败:', error)
      }
    }

    onMounted(() => {
      refreshData()
    })

    return {
      filterForm,
      categories,
      categoryDetails,
      detailDialogVisible,
      selectedCategoryDetail,
      categoryCountOption,
      categoryPriceOption,
      categoryPriceRangeOption,
      refreshData,
      applyFilter,
      resetFilter,
      viewCategoryDetail
    }
  }
}
</script>

<style scoped>
.category-analysis {
  height: 100vh;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.el-main {
  padding: 20px;
  background-color: #f5f5f5;
}

.filter-card {
  margin-bottom: 20px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
}

.detail-card {
  margin-bottom: 20px;
}
</style> 